package com.sinoglobal.sinostore.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import andbase.view.pullview.AbPullToRefreshView;
import andbase.view.pullview.AbPullToRefreshView.OnFooterLoadListener;
import andbase.view.pullview.AbPullToRefreshView.OnHeaderRefreshListener;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.BaseActivity;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.StateBaseActivity;
import com.sinoglobal.sinostore.adapter.EveryOneIsBuyAdapter;
import com.sinoglobal.sinostore.adapter.ScreenListAdapter;
import com.sinoglobal.sinostore.adapter.SearchTextAdapter;
import com.sinoglobal.sinostore.bean.ShopCityFirstVo;
import com.sinoglobal.sinostore.bean.ShopWareList;
import com.sinoglobal.sinostore.bean.ShopWareTypeVo;
import com.sinoglobal.sinostore.system.Constants;
import com.sinoglobal.sinostore.utils.ApiDebugUtil;
import com.sinoglobal.sinostore.utils.SharedPreferenceUtil;
import com.sinoglobal.sinostore.utils.TextUtil;
import com.sinoglobal.sinostore.widget.ExpandCollapseAnimation;
import com.sinoglobal.sinostore.widget.jazzy.JazzyGridView;
import com.yahoo.mobile.client.android.util.RangeSeekBar;
import com.yahoo.mobile.client.android.util.RangeSeekBar.ValueConvertable;

/**
 * @author LK
 * @title: GoodsListActivity.java
 * @package com.chiliring.sinostore.activity
 * @description: TODO(商品列表Activity)
 * @date 2015-1-14 上午10:54:45
 */
public class GoodsListActivity extends StateBaseActivity implements OnClickListener, OnHeaderRefreshListener, OnFooterLoadListener, OnCheckedChangeListener, OnItemClickListener {
    private static final int ALLTYPE = 1;
    private static final int SORT = 2;
    public static String cat_id = "0";
    public String sort_by = "0";
    public String sort_type = "1";
    private String filter = "1";
    ; //筛选类型：1=全部，2=现金，3=积分，4=现金+积分，默认为1，为1或者4下面两个条件传空
    private String filter1 = "";//筛选价格1，积分或者现金
    private String filter2 = "";//筛选价格2，积分或者现金

    /**
     * 返回按钮
     **/
    private ImageButton titleBtnBack;

    private AbPullToRefreshView shopwarelistGridview; //此 自定义GridView 是为了以后添加 下拉刷新和加载更多
    private JazzyGridView mGridView; // 商城列表页Gridview

    /**
     * 商品类型
     **/
    private CheckBox cbType;
    /**
     * 排序
     **/
    private CheckBox cbSort;
    /**
     * 筛选
     **/
    private CheckBox cbScrren;

    /**
     * 没有商品提示
     **/
    private TextView tvPrompt;

    private EditText etSearch;

    private EveryOneIsBuyAdapter shopWareListAdapter;

    private SearchTextAdapter searchTextAdapter;

    private PopupWindow mPopWin, popFilter;//,popSearchText;

    private View lastView;
    private View seekCashParent, seekCreditsParent;
    /**
     * 搜索布局
     **/
    private View layoutSearch;
    /**
     * 标题
     **/
    private TextView tvTitleName;
    /**
     * 右测按钮
     **/
    private TextView titleBtnRight;

    private ListView lvPopSearchText;
    private View popFilterBg;//pop空白处
    private View popSelectBg;//pop空白处
    private View popFilterView;//筛选的view

    /**
     * 筛选条件View
     **/
    private LinearLayout shopListChose;

    public static ArrayList<ShopWareTypeVo> shopWareTypeVos;

    /**
     * 类目集合
     **/
    private List<String> types = new ArrayList<String>();

    /**
     * 当前页
     **/
    private int pageIndex = 0;

    private RadioGroup rgFilterType;

    private TextView btnCompleteFilter;

    private RangeSeekBar<Float> seekCash, seekCredits;

    private int cashMin, cashMax, creditsMin, creditsMax;//

    private final byte DIVIDE_COUNTS = 9;

    private List<String> searchHistoryList = new ArrayList<String>();

    /**
     * 是否从首页进来
     **/
    private boolean isFirstPage = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_activity_goods_list);
        openChenJInShi();
        initView();
        initPopFilter();
        initPopSearchText();
        initData();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        lvPopSearchText.setVisibility(View.GONE);
        return super.onTouchEvent(event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        resetData(intent);
        ;
    }

    private void initView() {
        titleBtnBack = (ImageButton) this.findViewById(R.id.title_btn_left);
        titleBtnBack.setVisibility(View.VISIBLE);
        titleBtnBack.setOnClickListener(this);
        lvPopSearchText = (ListView) findViewById(R.id.lvPopSearch);
        etSearch = (EditText) findViewById(R.id.et_search_goods);
        etSearch.setFocusable(false);
        etSearch.setOnClickListener(this);
        layoutSearch = findViewById(R.id.layout_search);
        layoutSearch.setOnClickListener(this);
        tvTitleName = (TextView) this.findViewById(R.id.tv_title_name);
        titleBtnRight = (TextView) this.findViewById(R.id.title_btn_right);
        shopwarelistGridview = (AbPullToRefreshView) this.findViewById(R.id.shopwarelist_gridview);
        mGridView = (JazzyGridView) this.findViewById(R.id.mGridView);
        mGridView.setTransitionEffect();
        mGridView.setOnItemClickListener(this);
        shopListChose = (LinearLayout) this.findViewById(R.id.shop_list_chose);

        cbType = (CheckBox) this.findViewById(R.id.shop_type);
        cbSort = (CheckBox) this.findViewById(R.id.shop_sort);
        cbScrren = (CheckBox) this.findViewById(R.id.shop_screen);
        cbType.setOnCheckedChangeListener(this);
        cbSort.setOnCheckedChangeListener(this);
        cbScrren.setOnCheckedChangeListener(this);


        tvPrompt = (TextView) this.findViewById(R.id.tv_prompt);

        //设置监听器
        shopwarelistGridview.setOnHeaderRefreshListener(this);
        shopwarelistGridview.setOnFooterLoadListener(this);
        shopwarelistGridview.setPullRefreshEnable(false);
        shopwarelistGridview.setLoadMoreEnable(true);

        shopWareListAdapter = new EveryOneIsBuyAdapter(this);
        mGridView.setAdapter(shopWareListAdapter);

        titleBtnRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                toActivity(FirstActivity.class, null);
                GoodsListActivity.this.finish();
            }
        });
    }

    private int getSelectedCredits(Float value) {
        float maxValue = seekCredits.getAbsoluteMaxValue();
        int realValue;
        float val = value * 1.0f / maxValue;
        if (val < 1.0f / DIVIDE_COUNTS) {
            realValue = Math.round(val / (1.0f / DIVIDE_COUNTS) * 100);
        } else if (val < 3.0f / DIVIDE_COUNTS) {
            realValue = Math.round((val - 1.0f / DIVIDE_COUNTS) * 900 / (2.0f / DIVIDE_COUNTS)) + 100;
        } else if (val < 5.0f / DIVIDE_COUNTS) {
            realValue = Math.round((val - 3.0f / DIVIDE_COUNTS) * 1000 / (2.0f / DIVIDE_COUNTS)) + 1000;
        } else if (val < 7.0f / DIVIDE_COUNTS) {//2-10k积分
            realValue = Math.round((val - 5.0f / DIVIDE_COUNTS) * 8000 / (2.0f / DIVIDE_COUNTS)) + 2000;
            //			return "积分"+String.valueOf(realValue/1000)+"k";
        } else {//10-100k积分
            realValue = Math.round((val - 7.0f / DIVIDE_COUNTS) * 90000 / (2.0f / DIVIDE_COUNTS)) + 10000;
            //			return "积分"+ String.valueOf(realValue/1000)+"k";
        }
        return realValue;
    }

    private int getSelectedCash(Float value) {
        float maxValue = seekCash.getAbsoluteMaxValue();
        int realValue;
        float val = value * 1.0f / maxValue;
        if (val < 4.0f / DIVIDE_COUNTS) {
            realValue = Math.round(val / (4.0f / DIVIDE_COUNTS) * 100);
        } else if (val < 6.0f / DIVIDE_COUNTS) {
            realValue = Math.round((val - 4.0f / DIVIDE_COUNTS) * 100 / (2.0f / DIVIDE_COUNTS)) + 100;
        } else if (val < 8.0f / DIVIDE_COUNTS) {
            realValue = Math.round((val - 6.0f / DIVIDE_COUNTS) * 300 / (2.0f / DIVIDE_COUNTS)) + 200;
        } else {
            realValue = Math.round((val - 8.0f / DIVIDE_COUNTS) * 500 / (1.0f / DIVIDE_COUNTS)) + 500;
            //			return "积分"+String.valueOf(realValue/1000)+"k";
        }

        return realValue;
    }

    /**
     * 初始化数据
     */
    private void initData() {//
        isFirstPage = getIntent().getBooleanExtra("fromHomePage", true);
        if (isFirstPage) {
            shopListChose.setVisibility(View.VISIBLE);
            if (null != shopWareTypeVos && shopWareTypeVos.size() > 0) {
                int position = getIntent().getIntExtra("typePosition", 0);
                ShopWareTypeVo typeVo = shopWareTypeVos.get(position);
                Constants.Type_POSITION = position;
                cat_id = typeVo.getId();
                cbType.setText(typeVo.getName());
                if (types.isEmpty()) {
                    for (ShopWareTypeVo type : shopWareTypeVos) {
                        types.add(type.getName());
                    }
                }
            }
        } else {
            shopListChose.setVisibility(View.GONE);
            cat_id = getIntent().getStringExtra("typeId");
        }
        etSearch.setText(getIntent().getStringExtra("searchText"));
        loadData(true);
    }

    private void resetData(Intent intent) {
        etSearch.setText(intent.getStringExtra("searchText"));
//		cbSort.setText("默认排序");
//		cbType.setText("全部");
//		cbScrren.setText("筛选");
//		cbSort.setTextColor(getResources().getColor(R.color.text_deep_gray));
//		cbType.setTextColor(getResources().getColor(R.color.text_deep_gray));
//		cbScrren.setTextColor(getResources().getColor(R.color.text_deep_gray));
//
//		cat_id = "0";
//		sort_by = "0";
//		sort_type = "1";
//		filter = "1";; //筛选类型：1=全部，2=现金，3=积分，4=现金+积分，默认为1，为1或者4下面两个条件传空
//		filter1 = "";//筛选价格1，积分或者现金
//		filter2 = "";//筛选价格2，积分或者现金
        pageIndex = 0;
        loadData(true);
    }

    /**
     * @author LK
     * @methods loadData
     * @description 描述信息  请求数据
     * @date 2015-1-14 下午2:24:29 参数说明
     */
    private void loadData(boolean isShowDialog) {
        if ("筛选".equals(cbScrren.getText().toString())) {
            filter = "1";
        } else if ("全部".equals(cbScrren.getText().toString())) {
            filter = "1";
        } else if (getString(R.string.money_score).equals(cbScrren.getText().toString())) {//现金积分购买
            filter = "4";
        } else if (cbScrren.getText().toString().contains("￥")) {//现金购买
            filter = "2";
            filter1 = String.valueOf(getSelectedCash(seekCash.getSelectedMinValue()));
            float cashM = getSelectedCash(seekCash.getSelectedMaxValue());
            if (cashM < 1000) {
                filter2 = String.valueOf(cashM);
            } else {
                filter2 = "";
            }
        } else if (cbScrren.getText().toString().contains(getString(R.string.score_unit))) {//积分购买
            filter = "3";
            filter1 = String.valueOf(getSelectedCredits(seekCredits.getSelectedMinValue()));
            float creditsM = getSelectedCredits(seekCredits.getSelectedMaxValue());
            if (creditsM < 100000) {
                filter2 = String.valueOf(creditsM);
            } else {
                filter2 = "";
            }
        }
        final ProgressDialog progressDialog = new ProgressDialog(this);
        if (isShowDialog) {
            progressDialog.setMessage("加载中...");
            progressDialog.show();
        }
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("por", "101");
        params.addQueryStringParameter("proIden", Constants.STOREFLAG);
        params.addQueryStringParameter("cat_id", cat_id);
        params.addQueryStringParameter("sort_by", sort_by);
        params.addQueryStringParameter("sort_type", sort_type);
        params.addQueryStringParameter("filter", filter);
        params.addQueryStringParameter("filter1", filter1);
        params.addQueryStringParameter("filter2", filter2);
        params.addQueryStringParameter("name", etSearch.getText().toString());
        params.addQueryStringParameter("pageNum", String.valueOf(pageIndex));
        params.addQueryStringParameter("pageSize", "60");
        ApiDebugUtil.debug(params);
        httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {

            @Override
            public void onStart() {
                super.onStart();
                LogUtils.i("Result====" + this.getRequestUrl());
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }

            @SuppressLint("NewApi")
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                stopRefreshOrLoad();
                String result = responseInfo.result;
                if (!TextUtils.isEmpty(result)) {
                    LogUtils.e("result==" + result);
                    ShopCityFirstVo cityFirstVo;
                    try {
                        cityFirstVo = JSON.parseObject(result, ShopCityFirstVo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        showShortToast("数据解析错误");
                        return;
                    }
                    if (Constants.STORE_SUCCESS_CODE.equals(cityFirstVo.getCode())) {
//						mGridView.smoothScrollToPositionFromTop(0, 0);
                        Constants.PIC_HOST = cityFirstVo.getHost();
                        if (null != cityFirstVo.getList() && cityFirstVo.getList().size() > 0) {
                            shopwarelistGridview.setVisibility(View.VISIBLE);
                            tvPrompt.setVisibility(View.GONE);
                            if (pageIndex == 0) {
                                shopWareListAdapter.clearData();
                                if (android.os.Build.VERSION.SDK_INT >= 11) {
                                    mGridView.smoothScrollToPositionFromTop(0, 0, 0);
                                }
                            }
                            shopWareListAdapter.addData(cityFirstVo.getList());
                            int pageCount = 1;
                            pageIndex++;
                            try {
                                pageCount = Integer.parseInt(cityFirstVo.getPages());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (pageIndex > pageCount) {
                                shopwarelistGridview.setLoadMoreEnable(false);
                            } else {
                                shopwarelistGridview.setLoadMoreEnable(true);
                            }
                        } else {
                            if (pageIndex == 0) {
                                shopwarelistGridview.setVisibility(View.GONE);
                                tvPrompt.setVisibility(View.VISIBLE);
                                return;
                            }
                            showShortToast("到底啦，再拉就坏了~");
                        }
                    }
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.title_btn_left) {
            this.finish();
        } else if (id == R.id.btnSure) {
            //			popFilterView.setVisibility(View.GONE);
            Constants.SORT_POSITION = 0;
            setUpfilterCondition(0);
            cbSort.setText("默认排序");
            popFilter.dismiss();
            if (rgFilterType.getCheckedRadioButtonId() == R.id.rbCashBuy) {
                String text = seekCash.getValueConvertable().valueToLabelText(seekCash.getSelectedMinValue())
                        + "-" + seekCash.getValueConvertable().valueToLabelText(seekCash.getSelectedMaxValue()).replace("￥", "");
                cbScrren.setText(text);
            } else if (rgFilterType.getCheckedRadioButtonId() == R.id.rbCreditsBuy) {
                String text = seekCredits.getValueConvertable().valueToLabelText(seekCredits.getSelectedMinValue())
                        + "-" + seekCredits.getValueConvertable().valueToLabelText(seekCredits.getSelectedMaxValue()).replace(getString(R.string.score_unit), "");
                cbScrren.setText(text);
            } else {
                RadioButton radioButton = (RadioButton) rgFilterType.findViewById(rgFilterType.getCheckedRadioButtonId());
                if (radioButton != null) {
                    cbScrren.setText(radioButton.getText());
                } else {
                    cbScrren.setText("筛选");
                }
            }
            pageIndex = 0;
            loadData(true);
        } else if (id == R.id.et_search_goods
                || id == R.id.layout_search) {
            Bundle bundle = new Bundle();
            bundle.putString("searchText", etSearch.getText().toString());
            bundle.putBoolean("isList", true);
            toActivity(SearchListActivity.class, bundle);
        } else {
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Constants.Type_POSITION = 0;
        Constants.SORT_POSITION = 0;
    }

    @Override
    public void onFooterLoad(AbPullToRefreshView view) {
        loadData(false);
    }

    @Override
    public void onHeaderRefresh(AbPullToRefreshView view) {
        pageIndex = 0;
        loadData(false);
    }

    private void stopRefreshOrLoad() {
        shopwarelistGridview.onHeaderRefreshFinish();
        shopwarelistGridview.onFooterLoadFinish();
    }


    /**
     * @param msg
     * @author czz
     * @createdate 2014-10-15 下午3:44:38
     * @Description: (设置筛选条件)
     */
    private void setUpfilterCondition(int position) {
        /**1兑换数，2辣椒币，3售卖时间,4sort(默认),5现金
         * sort_by //1兑换数，2积分，3售卖时间，4推荐排序（默认）5，现金 sort_type//1降序(默认)，2升序 0、默认
         * 1、最新上架：售卖时间，降序； 2、兑换最多：兑换数，降序 3、价格最低：辣椒币，升序 4、价格最高：辣椒币，降序
         *
         * <item>默认排序</item>
         <item>购买最多</item>
         <item>最新上架</item>
         <item>积分最少</item>
         <item>现金最少</item>
         */
        switch (position) {
            case 0:
                sort_by = "4";
                sort_type = "0";
                break;
            case 1:
                sort_by = "1";
                sort_type = "1";
                break;
            case 2://最新上架
                sort_by = "6";
                sort_type = "1";
                break;
            case 3:
                sort_by = "2";
                sort_type = "2";
                if (cbScrren.getText().toString().contains("￥")) {//现金最少
                    sort_by = "5";
                    sort_type = "2";
                }
                break;
            case 4:
                sort_by = "5";
                sort_type = "2";
                break;
            default:
                sort_by = "0";
                sort_type = "1";
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        if (id == R.id.shop_type) {
            if (isChecked) {
                showPopupWindow(buttonView, ALLTYPE, types);
                cbType.setTextColor(getResources().getColor(R.color.title_bg_red));
                cbScrren.setTextColor(getResources().getColor(R.color.text_deep_gray));
                cbSort.setTextColor(getResources().getColor(R.color.text_deep_gray));
            } else {
                cbSort.setChecked(false);
                cbScrren.setChecked(false);
            }
        } else if (id == R.id.shop_sort) {
            if (isChecked) {
                List<String> data = Arrays.asList(getResources().getStringArray(R.array.shopware));
//				if ("积分兑换".equals(cbScrren.getText().toString())) {
                if (cbScrren.getText().toString().contains(getString(R.string.score_unit))
                        && !getString(R.string.money_score).equals(cbScrren.getText().toString())) {
                    data = Arrays.asList(getResources().getStringArray(R.array.shopware1));
                } else if (cbScrren.getText().toString().contains("￥")) {
                    data = Arrays.asList(getResources().getStringArray(R.array.shopware2));
                }
                showPopupWindow(buttonView, SORT, data);
                cbSort.setTextColor(getResources().getColor(R.color.title_bg_red));
                cbScrren.setTextColor(getResources().getColor(R.color.text_deep_gray));
                cbType.setTextColor(getResources().getColor(R.color.text_deep_gray));
            } else {
                cbScrren.setChecked(false);
                cbType.setChecked(false);
            }
        } else if (id == R.id.shop_screen) {
            if (isChecked) {
                cbScrren.setTextColor(getResources().getColor(R.color.title_bg_red));
                cbSort.setTextColor(getResources().getColor(R.color.text_deep_gray));
                cbType.setTextColor(getResources().getColor(R.color.text_deep_gray));
                //				popFilterView.setVisibility(View.VISIBLE);
                showPopFilter(buttonView);
            } else {
                cbSort.setChecked(false);
                cbType.setChecked(false);
            }
        } else {
        }
    }

    /**
     * @param v
     * @param data 参数说明
     * @author LK
     * @methods showPopupWindow
     * @description 描述信息 弹框
     * @date 2015-1-14 下午5:27:38
     */
    private void showPopupWindow(final View v, final int type, final List<String> data) {
        LinearLayout view = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.shop_layout_popup, null);
        ListView lv = (ListView) view.findViewById(R.id.lv_popup);
        lv.setAdapter(new ScreenListAdapter(this, type, data));
        mPopWin = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
                true);
        ColorDrawable drawable = new ColorDrawable(0x90000000);
        mPopWin.setBackgroundDrawable(drawable);
        mPopWin.showAsDropDown(v);
        mPopWin.update();
        mPopWin.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                cbScrren.setChecked(false);
                cbSort.setChecked(false);
                cbType.setChecked(false);
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                CheckBox text = (CheckBox) v;
                text.setText(data.get(position));
                switch (type) {
                    case 1:
                        cat_id = shopWareTypeVos.get(position).getId();
                        Constants.Type_POSITION = position;
                        break;
                    case 2:
                        Constants.SORT_POSITION = position;
                        setUpfilterCondition(position);
                        break;
                    default:
                        break;
                }
                mPopWin.dismiss();
                pageIndex = 0;
                loadData(true);
            }
        });
        popSelectBg = view.findViewById(R.id.popSelectBg);
        popSelectBg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mPopWin.dismiss();
            }
        });
    }

    private void showPopFilter(View v) {
        popFilter.update();
        popFilter.showAsDropDown(v);
    }

    private void initPopFilter() {
        popFilterView = LayoutInflater.from(this).inflate(
                R.layout.shop_pop_filter, null);
        popFilter = new PopupWindow(popFilterView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
                true);
        ColorDrawable drawable = new ColorDrawable(0x90000000);
        popFilter.setBackgroundDrawable(drawable);
        popFilter.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                cbScrren.setChecked(false);
                cbSort.setChecked(false);
                cbType.setChecked(false);
            }
        });
        rgFilterType = (RadioGroup) popFilterView.findViewById(R.id.rgFilterType);
        seekCashParent = rgFilterType.findViewById(R.id.seekCashParent);
        seekCreditsParent = rgFilterType.findViewById(R.id.seekCreditsParent);
        seekCash = (RangeSeekBar<Float>) popFilterView.findViewById(R.id.seekCash);
        seekCredits = (RangeSeekBar<Float>) popFilterView.findViewById(R.id.seekCredits);
        seekCash.setMinLabel("    ");
        seekCash.setMaxLabel("    ");
        seekCash.setValueConvertable(new ValueConvertable<Float>() {
            @Override
            public String valueToLabelText(Float value) {
                LogUtils.d("seekCredits.value==" + value);
                int realValue = getSelectedCash(value);
                if (realValue < 1000) {
                    return "￥" + String.valueOf(realValue);
                }
                return "不限";
            }
        });
        seekCredits.setMinLabel("    ");
        seekCredits.setMaxLabel("    ");
        seekCredits.setValueConvertable(new ValueConvertable<Float>() {
            @Override
            public String valueToLabelText(Float value) {
                LogUtils.d("seekCredits.value==" + value);
                int realValue = getSelectedCredits(value);

                String result = "不限";
                if (realValue < 1000) {
                    result = getString(R.string.score_unit) + String.valueOf(realValue);
                } else if (realValue < 100000) {
                    result = String.format("%s%.1fk", getString(R.string.score_unit), realValue / 1000f);
                } else {
                    result = "不限";
                }

                return result;
            }
        });
        rgFilterType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            private void animatePopFilter(View v, int type) {
                Animation anim = new ExpandCollapseAnimation(v, type);
                anim.setDuration(500);
                v.startAnimation(anim);
                if (type == ExpandCollapseAnimation.EXPAND) {
                    lastView = v;
                }
            }

            private void showAnimationView(View v) {
                if (lastView != null && lastView != v) {
                    animatePopFilter(lastView, ExpandCollapseAnimation.COLLAPSE);
                }
                int type = v.getVisibility() == View.VISIBLE ? ExpandCollapseAnimation.COLLAPSE : ExpandCollapseAnimation.EXPAND;
                animatePopFilter(v, type);
            }

            private void hidnAllAnnimationView() {
                if (lastView != null) {
                    animatePopFilter(lastView, ExpandCollapseAnimation.COLLAPSE);
                }
                lastView = null;
            }

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rbCashBuy) {
                    //					currentView=seekCashParent;
                    if (lastView == seekCashParent) {
                        lastView = null;
                    }
                    showAnimationView(seekCashParent);
                } else if (checkedId == R.id.rbCreditsBuy) {
                    //					currentView=seekCreditsParent;
                    if (lastView == seekCreditsParent) {
                        lastView = null;
                    }
                    showAnimationView(seekCreditsParent);
                } else if (checkedId == R.id.rbFilterNone
                        || checkedId == R.id.rbCashAndCredits) {
                    //					currentView=null;
                    hidnAllAnnimationView();
                } else {
                }
            }
        });
        btnCompleteFilter = (TextView) popFilterView.findViewById(R.id.btnSure);
        btnCompleteFilter.setOnClickListener(this);
        popFilterBg = popFilterView.findViewById(R.id.popFilterBg);
        popFilterBg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                popFilter.dismiss();
            }
        });
    }

    private void initPopSearchText() {
        String searchHistory = SharedPreferenceUtil.getString(this, "searchHistory");
        if (!TextUtil.stringIsNull(searchHistory)) {
            String[] searchArr = searchHistory.split(",");
            for (int i = 0; i < searchArr.length; i++) {
                searchHistoryList.add(searchArr[i]);
            }
        }
        searchTextAdapter = new SearchTextAdapter(this, searchHistoryList);
        lvPopSearchText.setAdapter(searchTextAdapter);
        lvPopSearchText.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                etSearch.setText(searchTextAdapter.getItem(position));
                refreshSearchHistory();
                //				popSearchText.dismiss();
                loadData(true);
            }
        });

    }

    private void refreshSearchHistory() {
        searchHistoryList.remove(etSearch.getText().toString());
        searchHistoryList.add(0, etSearch.getText().toString());
        if (searchHistoryList.size() > 5) {
            searchHistoryList = searchHistoryList.subList(0, 5);
        }
        searchTextAdapter.notifyDataSetChanged();
        lvPopSearchText.setVisibility(View.GONE);
        pageIndex = 0;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ShopWareList entity = (ShopWareList) shopWareListAdapter.getItem(position);
        Bundle bundle = new Bundle();
        bundle.putString("goodsId", entity.getId());
        toActivity(GoodsDetailActivity.class, bundle);
    }
}
